<%@page import="java.util.UUID"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/pages/common/taglib.jsp" %>
<%
    String uuid = UUID.randomUUID().toString();
    request.setAttribute("uuid", uuid);
%>

<div class="row">
	<div class="col-md-3">
		<div class="box box-primary">
    		<div class="box-header with-border">
    			<h3 class="box-title">
    			
    			</h3>
    			<div class="box-tools pull-right" id="orgToolForm_${uuid}">
    				<shiro:hasPermission name="ORG_MGR_ADD">
			    	<a href="javascript:void(0)" class="btn btn-sm btn-success addBt ">
			            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> 添加
			        </a>
			        </shiro:hasPermission>
			        
			        <shiro:hasPermission name="ORG_MGR_MOD">
			        <a href="javascript:void(0)" class="btn btn-sm btn-primary editBt ">
			            <span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 修改
			        </a>
			        </shiro:hasPermission>
			        
			        <shiro:hasPermission name="ORG_MGR_DEL">
			        <a href="javascript:void(0)" class="btn btn-sm btn-danger delBt ">
			            <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> 删除
			        </a>
			        </shiro:hasPermission>
    			</div>
    		</div>
    		<div class="box-body">
    			<div id="orgTree_${uuid}" class="ztree">
		    	</div>
    		</div>
    	</div>
	</div>
	<div class="col-md-9 container-fluid">
		<div class="nav-tabs-custom">
			<ul class="nav nav-tabs" role="tablist">
				<li class="active">
					<a href="#orgRelTab_${uuid}" role="tab" data-toggle="tab">
	    			<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> 关系配置
	    			</a>
				</li>
				<li>
	    			<a href="#orgExtConfigTab_${uuid }" role="tab" data-toggle="tab">
	    			<span class="glyphicon glyphicon-paperclip" aria-hidden="true"></span> 扩展配置
	    			</a>
	    		</li>
			</ul>
			<div class="tab-content">
				<div role="tabpanel" class="tab-pane active" id="orgRelTab_${uuid}">
					<div class="box-body">
		    			<div id="orgRel_${uuid}" class="row" style="display: none;">
							<pf:dataDic dicCode="ORG_REL_TYPE" var="item">
								<div class="col-md-4">
								<div class="panel am-margin-sm org-rel-type-item panel-primary" style="width:98%">
									  <div class="panel-heading">${item.name}</div>
									  
								      <ul class="list-group org-rel-type-item-content" id="${item.code}_relItems">
										       	
									  </ul>
									  <div class="panel-footer">
									  	  <shiro:hasPermission name="ORG_ATTR_MOD">
										  <a href="javascript:void(0)" data-code="${item.code}" data-value="${item.value}" class="btn  btn-sm  btn-default orgRelEditBt">
									         <span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 配置
									      </a>
									      </shiro:hasPermission>
								      </div>
								</div>
								</div>
							</pf:dataDic>
						</div>
		    		</div>
				</div>
				<div role="tabpanel" class="tab-pane" id="orgExtConfigTab_${uuid}">
					<div class="box-body">
		    			<div class="row">
		    				<pf:dataDic dicCode="ORG_EXT_CONFIG_TYPE" var="item">
								<div class="col-md-6">
									<div class="panel panel-default" style="width:98%" data-code="${item.code}" data-value="${item.value}">
										  <div class="panel-heading">${item.name}</div>
										  <div class="panel-body">
										  	无
										  </div>								  
									</div>
								</div>
							</pf:dataDic>
		    			</div>
		    		</div>
					
				</div>
			</div>
		</div>
	
	</div>
</div>

<script type="text/javascript">
    $(function () {
        var uuid = '${uuid}';
        var orgTree = $("#orgTree_"+uuid);
        var orgToolForm = $("#orgToolForm_"+uuid);
        
        $("#orgExtConfigTab_"+uuid+" .panel").each(function(i,n){
        	var value=eval('('+$(this).data("value")+')');
        	if(value.url.indexOf("?")<0){
        		value.url+="?_tmp=1";
        	}
        	$(this).data("url",value.url);
        });
        
        var editOrg=function(params){
            params = params || {};
            var t = [];
            if (params.id) {
                t.push("id=" + params.id);
            }
            if (params.pid) {
                t.push("pid=" + params.pid);
            }
            
            var dialog=webUtils.dialog({
              	 title:'编辑组织机构',
              	 url:ctx + '/orgAction/editView.do?' + t.join("&"),
              	 onremove:function () {
                       if (params.onClose) {
                           params.onClose.call(null);
                       }
                   }
               });
            return dialog;
        }

        orgToolForm.find(".addBt").click(function () {
            var nodes = orgTree.getSelectedNodes();
            if (nodes && nodes.length > 0) {
                var node = nodes[0];
                var sub = top.webUtils.topicSubscribe("org.edit.success", function (args) {
                    var cnode = args.obj;
                    orgTree.addNodes(node, cnode);
                    dialog.close();
                });
                var dialog = editOrg({
                    pid: node.id,
                    onClose: function () {
                        sub.remove();
                    }
                });
            } else {
                webUtils.alert("请选择其中一个");
            }
        });

        orgToolForm.find(".editBt").click(function () {
            var nodes = orgTree.getSelectedNodes();
            if (nodes && nodes.length > 0) {
                var node = nodes[0];
                var sub = top.webUtils.topicSubscribe("org.edit.success", function (args) {
                    var cnode = args.obj;
                    orgTree.updateNode($.extend(node, cnode));
                    dialog.close();
                });
                var dialog = editOrg({
                    id:node.id,
                    onClose: function () {
                        sub.remove();
                    }
                });
            } else {
                webUtils.alert("请选择其中一个");
            }
        });

        orgToolForm.find(".delBt").click(function () {
            var nodes = orgTree.getSelectedNodes();
            if (nodes && nodes.length > 0) {
            	webUtils.confirm("删除后将不可恢复，请问是否继续?", function(result) {
					if(result){
						var ids = [];
		                $.each(nodes, function (i, n) {
		                    ids.push(n.id);
		                });
		                $.post(ctx + "/orgAction/delOrg.do", {ids: ids.join(",")}, function (data) {
		                    if (data.success) {
		                        $.each(nodes, function (i, n) {
		                            orgTree.removeNode(n);
		                        });
		                    } else {
		                        webUtils.error(data.msg);
		                    }
		                }, 'json');
					}
        		});
            } else {
                alert("请勾选至少个");
            }
        });

        orgTree = $.fn.zTree.init(orgTree, {
            treeId: "orgTree",
            async: {
                enable: true,
                url: ctx + "/orgAction/queryOrgTreeNodes.do",
                autoParam: ["id=pid"],
                dataFilter: function (treeId, parentNode, responseData) {
                    if (responseData) {
                        $.each(responseData, function (i, n) {
                            if (n.childrenSize > 0) {
                                n.isParent = true;
                            }
                        });
                    }
                    return responseData;
                }
            },
            data: {
                key: {
                    name: "text"
                }
            },
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: false
                }
            },
            callback: {
                onDrop: function (e, treeId, treeNodes, targetNode, moveType, isCopy) {
                    if (treeNodes && treeNodes.length > 0) {
                        var treeNode = treeNodes[0];
                        var pNode = orgTree.getNodeByTId(treeNode.parentTId);
                        var ids = [];
                        $.each(pNode.children, function (i, n) {
                            ids.push(n.id);
                        });
                        $.post(ctx + "/orgAction/seqNodes.do", {ids: ids.join(","), pid: pNode.id}, function (data) {
                            if (data.success) {
                            } else {
                                webUtils.error(data.msg);
                            }
                        }, "json");
                    }
                },
                onClick: function (e, treeId, treeNode, clickFlag) {
                	if (clickFlag != 0) {
                		if(treeNode.id!=-1){
                			$("#orgRel_"+uuid).show();
                			refreshOrgRelExtAttrs(treeNode.id);
                			refreshOrgExtConfig(treeNode.id);
                		}else{
                			$("#orgRel_"+uuid).hide();
                		}
                		
                	}
                }
            }
        }, [{
                text: "组织机构",
                id: "-1",
                isParent: true,
                open: true
            }]);
        
        orgTree.reAsyncChildNodes(orgTree.getNodesByParam("id", "-1")[0], "refresh");
        
        // 1组织机构 2用户 3角色 4岗位 6字典 7自定义 
        $(".orgRelEditBt").click(function(){
        	var selectedRows=orgTree.getSelectedNodes();
        	var orgId=selectedRows[0].id;
        	var code=$(this).data("code");
        	var value=eval('('+$(this).data("value")+')');
        	if(value.type==1){
        		webUtils.orgSelector({
        			isSingle:value.single,
            		onSelect:function(rows){
            			var rels=[];
            			$.each(rows,function(i,n){
            				rels.push({
            					orgId:orgId,
            					extCode:code,
            					attrVal:n.id,
            					attrViewName:n.name,
            					attrType:value.type
            				})
            			});
            			addRel(code,rels,true,value.single);
            		} 
            	});
        	}else if(value.type==2){
        		webUtils.userSelector({
        			isSingle:value.single,
            		onSelect:function(rows){
            			var rels=[];
            			$.each(rows,function(i,n){
            				rels.push({
            					orgId:orgId,
            					extCode:code,
            					attrVal:n.id,
            					attrViewName:n.userName,
            					attrType:value.type
            				})
            			});
            			addRel(code,rels,true,value.single);
            		} 
            	});
        	}
        });
        
        
        
        
        function addRel(code,rels,saveToServer,isSingle){
        	var  relBox=$("#"+code+"_relItems");
        	if(isSingle){
        		relBox.find(".org-rel-type-item-val").each(function(i,n){
        			delOrgRelExtAttr($(n));
        		});
        	}
        	
        	$.each(rels,function(i,n){
        		if(relBox.find("li[val='"+n.attrVal+"']").size()<=0){
        			var isSaveSuccess=false;
            		if(saveToServer){
            			$.ajax({
            				async:false,
            				data:n,
            				dataType:"json",
            				type:"POST",
            				url:ctx+"/orgAction/saveOrgExtAttr.do",
            				success:function(data){
            					if(data.success){
            						isSaveSuccess=true;
            						n=data.obj;
            					}
            					
            				}
            			});
            		}else{
            			isSaveSuccess=true;
            		}
            		if(isSaveSuccess){
            			var html="<li class='list-group-item org-rel-type-item-val' val='"+n.attrVal+"'>"
           				+n.attrViewName
           	       		+'<button type="button" class="close delBtn" aria-label="Close"><span aria-hidden="true">&times;</span></button>'
           	       		+'</li>';
           	       		var dom=$(html);
           	       		dom.data("data",n);
           				relBox.append(dom);
            		}
        		}
        	});
        }
        
        function refreshOrgExtConfig(orgId){
        	$("#orgExtConfigTab_"+uuid+" .panel").each(function(i,n){
            	var url=$(this).data("url");
            	$(this).find(".panel-body").html("").load(ctx+url+"&orgId="+orgId);
            });
        }
        
        function refreshOrgRelExtAttrs(orgId){
        	$(".org-rel-type-item .org-rel-type-item-content").each(function(){
        		$(this).html("");
        	});
        	
        	$.getJSON(ctx+"/orgAction/loadOrgExtAttrs.do",{orgId:orgId},function(datas){
        		$.each(datas,function(i,n){
        			addRel(n.extCode,[n]);
        		})
        	});
        }
        
        $("#orgRel_"+uuid).delegate(".delBtn","click",function(){
        	var liDom=$(this).parent("li");
        	delOrgRelExtAttr(liDom);
        });
        
        function delOrgRelExtAttr(liDom){
        	var data=liDom.data("data");
        	$.ajax({
				async:false,
				data:{ids:data.id},
				dataType:"json",
				type:"POST",
				url:ctx+"/orgAction/delOrgExtAttrs.do",
				success:function(r){
					if(r.success){
	        			liDom.remove();
	        		}else{
	        			webUtils.error(r.msg);
	        		}
				}
			});
        }
        
        
    });
</script>